const pool = require('../config/db');

const getOrders = async (userId) => {
    const [rows] = await pool.execute(
        `SELECT o.*, s.name as store_name, s.logo as store_logo 
         FROM orders o 
         LEFT JOIN stores s ON o.store_id = s.id 
         WHERE o.user_id = ? 
         ORDER BY o.create_time DESC`, 
        [userId]
    );
    return rows;
};

const getOrderDetail = async (orderId, userId) => {
    const [rows] = await pool.execute(
        `SELECT o.*, s.name as store_name, s.logo as store_logo, s.address as store_address, s.contact_phone as store_phone
         FROM orders o 
         LEFT JOIN stores s ON o.store_id = s.id 
         WHERE o.id = ? AND o.user_id = ?`, 
        [orderId, userId]
    );
    return rows[0];
};

const insertOrder = async (orderData) => {
    const { user_id, store_id, order_no, total_price, final_price, payment_method, status, create_time, coupon_id } = orderData;
    
    const [result] = await pool.execute(
        `INSERT INTO orders (user_id, store_id, order_no, total_price, final_price, payment_method, status, create_time, coupon_id) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [user_id, store_id, order_no, total_price, final_price, payment_method, status, create_time, coupon_id || null]
    );
    
    return result.insertId;
};

const updateOrder = async (orderId, userId, updateData) => {
    const { status } = updateData;
    
    const [result] = await pool.execute(
        `UPDATE orders SET status = ?, update_time = NOW() 
         WHERE id = ? AND user_id = ?`,
        [status, orderId, userId]
    );
    
    return result;
};

module.exports = { getOrders, getOrderDetail, insertOrder, updateOrder };